package com.epam.training;

import java.math.BigDecimal;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.epam.training.domain.Car;
import com.epam.training.service.car.CarService;

@Controller
public class AddCarController {
	private final CarService service;

	@Autowired
	public AddCarController(CarService service) {
		this.service = service;
	}

	@ModelAttribute
	private Car createCar(@RequestParam String cModel,
			@RequestParam String cColor, @RequestParam Integer cConsumption,
			@RequestParam double cEngineVolume, @RequestParam String cGearbox,
			@RequestParam Integer cPower, @RequestParam Integer cTankCapacity,
			@RequestParam String cYear, @RequestParam BigDecimal cPrice) {

		Car car = new Car();
		car.setModel(cModel);
		car.setColor(cColor);
		car.setConsumption(cConsumption);
		car.setEngineVolume(cEngineVolume);
		car.setGearbox(cGearbox);
		car.setPower(cPower);
		car.setTankCapacity(cTankCapacity);
		car.setYear(cYear);
		car.setPrice(cPrice);

		return car;
	}

	@RequestMapping(value = "/admin/addCar", method = RequestMethod.POST)
	private String addNewCar(@ModelAttribute Car car, Model model) {
		service.save(car);

		model.addAttribute("message", "car.added");

		return AdminPageController.ADMIN_PAGE;
	}

	@RequestMapping(value = "/admin/updateCar")
	private String updateCar(@ModelAttribute Car car,
			@RequestParam Integer carId, Model model) {
		service.update(car, carId);

		model.addAttribute("message", "messeage.car.change");

		return AdminPageController.ADMIN_PAGE;
	}

}
